<?php

namespace app\api\controller;

use app\admin\model\ClassAddress;
use app\admin\model\Club;
use app\admin\model\ClubDtl;
use app\admin\model\Invoice;
use app\admin\model\Order;
use app\admin\model\OrderClassHours;
use app\admin\model\TeacherClass;
use app\admin\model\TeacherClassDtl;
use app\admin\model\TeacherSubscribe;
use app\common\controller\Api;
use app\common\model\Test;
use WeChatPay\Builder;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Formatter;
use WeChatPay\Util\PemUtil;

/**
 * 发票接口
 */
class InvoiceApi extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    //发票中心列表
    public function order_invoice_list(){
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }

        $query = Order::where(['user_id'=>$user['id']]);
        $query->with(['teachers','classmain']);
        if(isset($params['invoice_status'])&&$params['invoice_status']){
            if($params['invoice_status'] == 3){
                $params['invoice_status'] = 0;
            }
            $query->where(['invoice_status'=>$params['invoice_status']]);
        }
        $query->where(['pay_status'=>2]);
        $query = $query->order('id','desc')->paginate($params['page_size']);

        $list = $query->getCollection();

        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['order_id'] = $v['id'];
            $arr[$k]['avatar'] = '';
            if(isset($v['teachers'])){
                if(isset($v['teachers']['user'])){
                    $arr[$k]['avatar'] = $v['teachers']['user']['avatar'];
                }
            }

            $info = json_decode($v['info'],true);
            $arr[$k]['name'] = $info['name'];
            $arr[$k]['club_two'] = $info['club_two'];
            $classmain = isset($v['classmain']) ? $v['classmain'] : [];
            $status = '';
            $appointment_made_date = '';
            $class_progress = '';
            if($classmain){
                switch ($classmain['status']){
                    case 1:
                        $status = '未完成';
                        break;
                    case 2:
                        $status = '已完成';
                        break;
                    case 3:
                        $status = '已中止';
                        break;
                    default:
                        $status = '';
                        break;
                }
                $appointment_made_date = '';
                foreach ($classmain['dtls'] as $kk=>$vv){
                    if($kk == 0){
                        $appointment_made_date = $vv['week_date'];
                    }else{
                        $date_time = '/'.$vv['week_date'];
                        $appointment_made_date .= $date_time;
                    }
                }
                $class_progress = $classmain['completed_class_num'].'/'.$classmain['class_num_all'];

            }
            $arr[$k]['status'] = $status;
            $arr[$k]['appointment_made_date'] = $appointment_made_date;
            $arr[$k]['class_progress'] = $class_progress;
            $arr[$k]['money'] = (double)$v['money'];
            switch ($v['invoice_status']){
                case 0:
                    $invoice_status = '未开票';
                    break;
                case 1:
                    $invoice_status = '开票中';
                    break;
                case 2:
                    $invoice_status = '已开票';
                    break;
                default :
                    $invoice_status = '';
                    break;
            }
            $arr[$k]['invoice_status'] = $invoice_status;
            $invoice = Invoice::whereRaw("FIND_IN_SET('{$v['id']}', order_id)")->order('id','desc')->find();
            $arr[$k]['invoice_file'] = isset($invoice['invoice_file']) ? $invoice['invoice_file'] : '';
            $arr[$k]['invoice_id'] = isset($invoice['id']) ? $invoice['id'] : '';
            $class = TeacherClass::where(['order_no'=>$v['order_no']])->find();
            $arr[$k]['class_id'] = isset($class['id']) ? $class['id'] : '';
        }

        $count = $query->total();
        $data['list'] = $arr;
        $data['count'] = $count;

        $this->success('发票中心列表',$data);
    }

    //开票
    public function add_invoice(){
        $params = $this->request->param();
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }

        if(!isset($params['order_id'])||!$params['order_id']){
            $this->error('订单id未传');
        }
        if(!isset($params['money'])||!$params['money']){
            $this->error('开票总额必填');
        }
        if(!isset($params['company_name'])||!$params['company_name']){
            $this->error('公司抬头必填');
        }
        if(!isset($params['company_tax_number'])||!$params['company_tax_number']){
            $this->error('公司税号必填');
        }
        $order_ids = explode(',',$params['order_id']);
        $order_find = Order::whereIn('id',$order_ids)->whereIn('invoice_status',[1,2])->select();
        if($order_find){
            $this->error('存在已开票或者开票中的订单');
        }
        $add = [];
        $add['user_id'] = $user['id'];//用户id
        $add['order_id'] = $params['order_id'];//订单id
        $add['money'] = $params['money'];//开票总额
        $add['company_name'] = $params['company_name'];//公司抬头
        $add['company_tax_number'] = $params['company_tax_number'];//公司税号
        $add['company_address'] = isset($params['company_address']) ? $params['company_address'] : '';//公司地址
        $add['company_phone'] = isset($params['company_phone']) ? $params['company_phone'] : '';//公司电话
        $add['opening_bank'] = isset($params['opening_bank']) ? $params['opening_bank'] : '';//开户银行
        $add['account_number'] = isset($params['account_number']) ? $params['account_number'] : '';//开户账号
        $add['status'] = 1;//状态 1申请中 2已开票 3已驳回
        $save = Invoice::create($add);
        if($save){
            Order::whereIn('id',$order_ids)->update(['invoice_status'=>1]);
            $this->success('已申请',$save);
        }else{
            $this->error('申请失败');
        }
    }

    //开票列表
    public function invoice_list(){
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }

        $query = Invoice::where(['user_id'=>$user['id']]);
        if(isset($params['status'])&&$params['status']){
            $query->where(['status'=>$params['status']]);
        }
        $query = $query->order('id','desc')->paginate($params['page_size']);

        $list = $query->getCollection();

        $arr = [];
        foreach ($list as $k=>$v){
            $arr[$k]['id'] = $v['id'];
            $arr[$k]['money'] = (double)$v['money'];
            $arr[$k]['company_name'] = $v['company_name'];
            $arr[$k]['company_tax_number'] = $v['company_tax_number'];
            switch ($v['status']){
                case 1:
                    $invoice_status = '申请中';
                    break;
                case 2:
                    $invoice_status = '已开票';
                    break;
                case 3:
                    $invoice_status = '已驳回';
                    break;
                default :
                    $invoice_status = '';
                    break;
            }
            $arr[$k]['status_name'] = $invoice_status;
            $arr[$k]['invoice_file'] = isset($v['invoice_file']) ? $v['invoice_file'] : '';
        }

        $count = $query->total();
        $data['list'] = $arr;
        $data['count'] = $count;

        $this->success('已开票列表',$data);
    }

    //开票详情
    public function invoice_detail(){
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }
        $params = $this->request->param();
        if(!isset($params['id'])||!$params['id']){
            $this->error('缺少id参数');
        }
        $invoice = Invoice::where(['id'=>$params['id']])->find();

        if(!$invoice){
            $this->error('数据不存在');
        }
        $order_ids = explode(',',$invoice['order_id']);
        $order = Order::whereIn('id',$order_ids)->select();
        $arr = [];
        foreach ($order as $k=>$v){
            $info = json_decode($v['info'],true);
            $arr[$k]['name'] = $info['name'];
            $class = TeacherClass::where(['order_no'=>$v['order_no']])->find();
            $arr[$k]['class_id'] = isset($class['id']) ? $class['id'] : '';
            $arr[$k]['club_two'] = $info['club_two'];
            $arr[$k]['money'] = (double)$v['money'];
        }
        $invoice['dtl'] = $arr;
        $data['list'] = $invoice;
        $this->success('开票详情',$data);
    }

}
